<?php

class ctrl_interview extends ctrl_base
{
    public static function index()
    {
        self::is_sales_user();
        self::smarty()->assign('user_type', $_SESSION['wx_userinfo']['user_type']);

        //$appid = 'wx4e66b2f84e2f18c3';
        //$appsecret = '7cfec6f2ba3befba75123d0acd09eab7';

        $jssdk = new ctrl_jssdk(APPID,APPSECRET);
        //$jssdk = new ctrl_jssdk($appid, $appsecret);
        $config = $jssdk->getSignPackage();
        //print_r($config);
        self::smarty()->assign('config', $config);

        // self::smarty() -> assign('user_type',1);
        self::smarty()->display('interview_index.html');
    }

    //判断当前用户是否是内部用户
    private static function is_sales_user()
    {
        self::weixin_check_login();
        if ($_SESSION['wx_userinfo']['user_type'] != 1) { //非内部用户
            echo "<script>alert('您好！此服务仅供日钢业务员使用，请先注册成为内部用户！');document.location.href = '/index.php?act=register';</script>";
            exit;
        }
    }

    //售前走访信息录入页面
    public static function pre_sales()
    {
        self::is_sales_user();
        self::smarty()->display('interview_pre_sales.html');
    }

    //保存售前走访信息
    public static function presalesSave()
    {
        self::is_sales_user();
        $data = array();
        $data['sales_id'] = $_SESSION['wx_userinfo']['openid'];
        $data['visit_unit'] = trim($_POST['visit_unit']);
        if (empty($data['visit_unit'])) {
            $errMsg = '走访单位名称不为空!';
            self::smarty()->assign("result_class", 'icon67_status warn');
            self::smarty()->assign("errMsg", $errMsg);
            self::smarty()->display('show_result.html');
            exit;
        }
        $data['visit_addr'] = trim($_POST['visit_addr']);
        if (empty($data['visit_addr'])) {
            $errMsg = '用户详细地址不为空!';
            self::smarty()->assign("result_class", 'icon67_status warn');
            self::smarty()->assign("errMsg", $errMsg);
            self::smarty()->display('show_result.html');
            exit;
        }
        $data['recevie_name'] = trim($_POST['recevie_name']);
        if (empty($data['recevie_name'])) {
            $errMsg = '接待人姓名不为空!';
            self::smarty()->assign("result_class", 'icon67_status warn');
            self::smarty()->assign("errMsg", $errMsg);
            self::smarty()->display('show_result.html');
            exit;
        }
        $data['recevie_study'] = trim($_POST['recevie_study']);
        $data['recevie_mobile'] = trim($_POST['recevie_mobile']);
        $data['recevie_email'] = trim($_POST['recevie_email']);
        $data['recevie_facts'] = trim($_POST['recevie_facts']);
        $data['recevie_question'] = trim($_POST['recevie_question']);
        $data['recevice_mind'] = trim($_POST['recevice_mind']);
        $data['recevie_date'] = date('Y-m-d H:i:s');

        $reult = model_interview::add_interview_record($data);
        if ($reult > 0) {
            self::smarty()->assign("result_class", 'icon67_status');
            self::smarty()->assign("errMsg", '客户售前走访信息录入成功！');
            self::smarty()->display('show_result.html');
        } else {
            self::smarty()->assign("result_class", 'icon67_status warn');
            self::smarty()->assign("errMsg", '信息录入失败！');
            self::smarty()->assign("comment", '系统异常，请稍后重试！');
            self::smarty()->display('show_result.html');
        }
    }

    //售后走访信息录入页面
    public static function aftermarket()
    {
        self::is_sales_user();
        self::smarty()->display('interview_aftermarket.html');
    }

    //保存售后走访信息
    public static function aftermarketSave()
    {
        self::is_sales_user();
        $customer_info = array();
        //$data['sales_id'] = $_SESSION['wx_userinfo']['openid'];
        $customer_info['customer_name'] = trim($_POST['customer_name']);
        if (empty($customer_info['customer_name'])) {
            $errMsg = '客户名称不为空!';
            self::smarty()->assign("result_class", 'icon67_status warn');
            self::smarty()->assign("errMsg", $errMsg);
            self::smarty()->display('show_result.html');
            exit;
        }
        $customer_info['province'] = trim($_POST['province']);
        $customer_info['city'] = trim($_POST['city']);
        $customer_info['area'] = trim($_POST['area']);
        $customer_info['street'] = trim($_POST['street']);
        $customer_info['general'] = trim($_POST['general']);
        $customer_info['ability'] = trim($_POST['ability']);
        $customer_info['status'] = trim($_POST['status']);
        $customer_info['part'] = trim($_POST['part']);
        $customer_info['sale_name'] = trim($_POST['sale_name']);
        $customer_info['author'] = $_SESSION['wx_userinfo']['openid'];
        $customer_info_id = model_interview::add_interview_record($customer_info, 'weixin_customer_info');
        if ($customer_info_id == 0) {
            self::smarty()->assign("result_class", 'icon67_status warn');
            self::smarty()->assign("errMsg", '客户信息录入失败！');
            self::smarty()->assign("comment", '系统异常，请稍后重试！');
            self::smarty()->display('show_result.html');
            exit;
        }
        //问题描述
        $qs['question_list'] = $_POST['question'];
        $qs['question_desc_list'] = $_POST['question_desc'];
        $question_count = count($qs['question_list']);
        if ($question_count == 1) {
            $question['customer_info_id'] = $customer_info_id;
            $question['question'] = trim($qs['question_list'][0]);
            $question['question_desc'] = trim($qs['question_desc_list'][0]);
            if (!empty($question['question'])) {
                $reult = model_interview::add_interview_record($question, 'weixin_customer_question');
            }
        } elseif ($question_count > 1) {
            for ($i = 0; $i < $question_count; $i++) {
                $question['customer_info_id'] = $customer_info_id;
                $question['question'] = trim($qs['question_list'][$i]);
                $question['question_desc'] = trim($qs['question_desc_list'][$i]);
                if (!empty($question['question'])) {
                    $reult = model_interview::add_interview_record($question, 'weixin_customer_question');
                }
            }
        }
        //收集人信息
        $data['customer_info_id'] = $customer_info_id;
        $data['collection_date'] = trim($_POST['collection_date']);
        $data['collection_channel'] = trim($_POST['collection_channel']);
        $data['collection_name'] = trim($_POST['collection_name']);
        $data['collection_part'] = trim($_POST['collection_part']);
        $data['collection_tel'] = trim($_POST['collection_tel']);

        $data['agreement'] = trim($_POST['agreement']);
        $data['product'] = trim($_POST['product']);
        $data['grade'] = trim($_POST['grade']);
        $data['format'] = trim($_POST['format']);
        if (isset($_POST['number']) && trim($_POST['number']) != '') {
            $data['number'] = trim($_POST['number']) . '吨';
        } else {
            $data['number'] = '';
        }
        $data['betch'] = trim($_POST['betch']);
        $data['occur_date'] = trim($_POST['occur_date']);
        $data['person_name'] = trim($_POST['person_name']);
        $data['person_study'] = trim($_POST['person_study']);
        $data['person_tel'] = trim($_POST['person_tel']);

        $reult = model_interview::add_interview_record($data, 'weixin_question_info');
        if ($reult == 0) {
            self::smarty()->assign("result_class", 'icon67_status warn');
            self::smarty()->assign("errMsg", '客户售后走访信息录入失败！');
            self::smarty()->assign("comment", '系统异常，请稍后重试！');
            self::smarty()->display('show_result.html');
            exit;
        } else {
            self::smarty()->assign("result_class", 'icon67_status');
            self::smarty()->assign("errMsg", '客户售后走访信息录入成功！');
            self::smarty()->display('show_result.html');
        }
    }


    //走访录入
    public static function visitEntry()
    {

        //$appid = 'wx4e66b2f84e2f18c3';appsecret = '7cfec6f2ba3befba75123d0acd09eab7';
        $appid = APPID;
        $appsecret = APPSECRET;
        $jssdk = new ctrl_jssdk($appid, $appsecret);
        $config = $jssdk->getSignPackage();
        self::smarty()->assign('config', $config);


        self::is_sales_user();
        //获取归属单位
        $list = model_interview::getUnitCategory();
        self::smarty()->assign("time", date('Y-m-d H:i'));
        self::smarty()->assign("list", $list);
        self::smarty()->display('visitEntry.html');

    }

    //走访录入
    public static function visitEntryDone()
    {
        //检查数据
        $insertDate = array();
        if (empty($_POST['visit_name'])) {
            echo json_encode(array('code' => 'fail'));
            exit;
        }
        $insertDate['visit_custorm'] = trim($_POST['visit_name']);

        if (empty($_POST['visit_addr'])) {
            echo json_encode(array('code' => 'fail'));
            exit;
        }
        $insertDate['custorm_addr'] = trim($_POST['visit_addr']);

        if (empty($_POST['recevie_name'])) {
            echo json_encode(array('code' => 'fail'));
            exit;
        }
        $insertDate['recive_name'] = trim($_POST['recevie_name']);
        $insertDate['recive_study'] = trim($_POST['recevie_study']);
        $insertDate['recive_tel'] = trim($_POST['recevie_mobile']);

        /*if(empty($_POST['recevie_study'])){
            echo json_encode(array('code'=>'fail'));exit;
        }
        if(empty($_POST['recevie_mobile'])){
            echo json_encode(array('code'=>'fail'));exit;
        }
        if(empty($_POST['recevie_email'])){
            echo json_encode(array('code'=>'fail'));exit;
        }*/

        $insertDate['recive_email'] = trim($_POST['recevie_email']);

        if (empty($_POST['name'])) {
            echo json_encode(array('code' => 'fail'));
            exit;
        }
        $insertDate['visiter_name'] = trim($_POST['name']);

        if (empty($_POST['unit'])) {
            echo json_encode(array('code' => 'fail'));
            exit;
        }

        if (empty($_POST['time'])) {
            echo json_encode(array('code' => 'fail'));
            exit;
        }


        $insertDate['business_unit'] = trim($_POST['unit']);
        $insertDate['user_recent'] = trim($_POST['recevie_facts']);
        $insertDate['cooperation'] = trim($_POST['recevie_question']);
        $insertDate['openids'] = $_SESSION['wx_userinfo']['openid'];
        $insertDate['visiter_date'] = trim($_POST['time']);
        $insertDate['image'] = trim($_POST['imgUrl']);

        //查询权限
        $type = 1;
        $typeList = model_interview::getUserTypeList($type);
        $visible = '';
        foreach($typeList as $cateid){
            if(empty($visible)){
                $visible = $type.'_'.$cateid['user_category_id'];
            }else{
                $visible .= ','.$type.'_'.$cateid['user_category_id'];
            }
        }
        $insertDate['visible'] = $visible;

        framework_static_function::write_log(json_encode($insertDate), 'visit');
        $result = model_interview::insertIntoVisited($insertDate);
        if ($result > 0) {
            echo json_encode(array('code' => 'success'));
        } else {
            echo json_encode(array('code' => 'fail'));
        }

    }

    public static function success()
    {
        self::smarty()->display('show_success.html');
    }


    //走访查询
    public static function visitSearch()
    {
        self::is_sales_user();
        $keys = $_POST['key'];
        self::smarty()->assign("key", $keys);

        //查询
        if (!empty($keys)) {
            $openId = $_SESSION['wx_userinfo']['openid'];

            if (!empty($_SESSION['wx_userinfo']['user_type'])) {
                $visible = ctrl_news::get_visible_str($openId, $_SESSION['wx_userinfo']['user_type']);
            } else {
                $userInfo = model_user::get_user_by_openid($openId, WEIXINHAO);
                if (!empty($userInfo['user_type'])) {
                    $visible = ctrl_news::get_visible_str($openId, $userInfo['user_type']);
                } else {
                    $visible = "*_*";//微信可见用户，*_* 表示所有用户可见
                }
            }
            framework_static_function::write_log(__METHOD__ . ":" . $visible, 'weixin_sql');
            // $openId = 'oX2IxuHfyFS7LsOvaOoKwoVmJMjE';

            $list = model_interview::searchVisit($keys, $visible);
            foreach ($list as $key => $value) {
                $list[$key]['visiter_date'] = substr($value['visiter_date'], 0, 10);
            }
            self::smarty()->assign("list", $list);
            if (empty($list)) {
                self::smarty()->assign("showNo", 'yes');
            }
        }


        self::smarty()->display('visitSearch.html');
    }

    //走访查询
    public static function visitSearchInfo()
    {
        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        if ($id == 0) {
            header("Content-type: text/html; charset=utf-8");
            exit("非法访问！");
        }
        $openId = $_SESSION['wx_userinfo']['openid'];
        //$openId = 'oX2IxuHfyFS7LsOvaOoKwoVmJMjE';
        $info = model_interview::getVisitInfo($id, $openId);
        //查询归属
        $list = model_interview::getUnitCategory();
        foreach ($list as $key => $value) {
            if ($value['unit_category_id'] == $info['custorm_unit']) {
                $info['custorm_unit'] = $value['category_name'];
            }
        }

        if (empty($info)) {
            header("Content-type: text/html; charset=utf-8");
            exit("非法访问！");
        }
        self::smarty()->assign('info', $info);
        self::smarty()->display("visitSearchInfo.html");
    }

    public function ajaxUpload()
    {
        $picname = $_FILES['mypic']['name'];
        $picsize = $_FILES['mypic']['size'];
        if ($picname != "") {
            //压缩图片

            if ($picsize > 10240000) {
                echo '图片大小不能超过10M';
                exit;
            }
            $type = strstr($picname, '.');
            if ($type != ".gif" && $type != ".jpg" && $type != ".png") {
                echo '图片格式不对！';
                exit;
            }
            $rand = rand(100, 999);
            $pics = date("YmdHis") . $rand . $type;
            //上传路径
            $pic_path = WEB_ROOT . "/files/upload/" . $pics;
            move_uploaded_file($_FILES['mypic']['tmp_name'], $pic_path);
            $new_pic_path = WEB_ROOT . "/files/upload/s" . $pics;
            self::mt($pic_path, $new_pic_path);
            @unlink($pic_path);
        }
        $size = round($picsize / 1024, 2);
        $arr = array(
            'name' => $picname,
            'pic' => HOST_URL . '/files/upload/s' . $pics,
            'size' => $size
        );
        echo json_encode($arr);

    }

    function mt($srcFile, $dstFile, $max_width = 1500, $max_height = 1500, $imgQuality = 90)
    {
        $data = @getimagesize($srcFile);
        framework_static_function::write_log('图片大小：' . json_encode($data), 'img');
        if ($data[0] <= $data[1] and $data[1] >= $max_height) {
            $height = $max_height;
            $width = intval($height * $data[0] / $data[1]);
        }
        if ($data[0] >= $data[1] and $data[0] >= $max_width) {
            $width = $max_width;
            $height = intval($width * $data[1] / $data[0]);
        }
        if ($height > $max_height) {
            $height = $max_height;
            $width = intval($height * $data[0] / $data[1]);
        }
        if ($data[0] < $max_width and $data[1] < $max_height) {
            $width = $data[0];
            $height = $data[1];
        }

        framework_static_function::write_log('缩放大小：' . $width . 'X' . $height, 'img');

        switch ($data[2]) {
            case 1:
                $im = @imagecreatefromgif($srcFile);
                break;
            case 2:
                $im = @imagecreatefromjpeg($srcFile);
                break;
            case 3:
                $im = @imagecreatefrompng($srcFile);
                break;
        }
        $srcW = @imagesx($im);
        $srcH = @imagesy($im);

        framework_static_function::write_log('画板大小：' . $srcW . 'X' . $srcH, 'img');

        $ni = @imagecreatetruecolor($width, $height);
        @imagecopyresampled($ni, $im, 0, 0, 0, 0, $width, $height, $srcW, $srcH);
        if ($srcW != $width) {
            $ni = imagerotate($ni, -90, 0);
        }
        switch ($data[2]) {
            case 'gif':
                @imagepng($ni, $dstFile, $imgQuality);
                break;
            case 'jpeg':
                @imagejpeg($ni, $dstFile, $imgQuality);
                break;
            case 'png':
                @imagepng($ni, $dstFile, $imgQuality);
                break;
            default:
                @imagejpeg($ni, $dstFile, $imgQuality);
                break;
        }
    }

}
